﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data.Objects;

namespace ImportOrders
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        SalesManagerEntities _sme = new SalesManagerEntities();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnSelectFile_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            if ((bool)dlg.ShowDialog())
            {
                txtFileName.Text = dlg.FileName;
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ((CollectionViewSource)FindResource("Owners")).Source = (from c in _sme.tblOwner select c);
            ((CollectionViewSource)FindResource("ImportSpecifications")).Source = _sme.tblImportSpec;
        }

        private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            gridErrors.ItemsSource = null;

            txtResults.Text = string.Empty;
            if (cmbOwner.SelectedValue == null)
            {
                MessageBox.Show("Select a valid owner");
                return;
            }
            Int32 ownerID = (Int32)cmbOwner.SelectedValue;

            if (cmbImportSpec.SelectedValue == null)
            {
                MessageBox.Show("Select a valid import specification");
                return;
            }
            tblImportSpec importSpec = (tblImportSpec)cmbImportSpec.SelectedItem;

            if (!System.IO.File.Exists(txtFileName.Text))
            {
                MessageBox.Show("File not found.");
                return;
            }

            SqlConnection conn = (SqlConnection)((System.Data.EntityClient.EntityConnection)_sme.Connection).StoreConnection;
            if (conn.State != System.Data.ConnectionState.Open)
                conn.Open();
            SqlCommand cmm = conn.CreateCommand();
            cmm.CommandType = System.Data.CommandType.StoredProcedure;

            // Load the file into a table using the specified template file.
            //cmm.CommandText = "ImportFromFile";
            //cmm.Parameters.Add(new SqlParameter("@tableName", importSpec.TableName));
            //cmm.Parameters.Add(new SqlParameter("@FileName", txtFileName.Text));
            //cmm.Parameters.Add(new SqlParameter("@templateFile", importSpec.TemplateFile));
            //try
            //{
            //    cmm.ExecuteNonQuery();
            //}
            //catch ( Exception err )
            //{
            //    MessageBox.Show("Error loading file.\n" + err.Message);
            //    return;
            //}

            // Run the stored procedure to load the orders
            cmm.CommandText = importSpec.StoredProcedure;
            cmm.CommandTimeout = 600; // Set the timeout to 10 minutes
            cmm.Parameters.Clear();
            cmm.Parameters.Add(new SqlParameter("@ReturnValue", System.Data.SqlDbType.Int)).Direction = System.Data.ParameterDirection.ReturnValue;
            cmm.Parameters.Add(new SqlParameter("@OwnerID", cmbOwner.SelectedValue));
            cmm.Parameters.Add(new SqlParameter("@FileName", txtFileName.Text));
            cmm.Parameters.Add(new SqlParameter("@TemplateFile", (importSpec.TemplateFile == null) ? DBNull.Value : (object)importSpec.TemplateFile));
            cmm.Parameters.Add(new SqlParameter("@TransformProcedure", (importSpec.TransformProcedure == null) ? DBNull.Value : (object)importSpec.TransformProcedure));
            SqlDataReader rdr = null;
            Cursor saveCursor = this.Cursor;
            try
            {
                this.Cursor = Cursors.Wait;
                Int32 importBatchID = 0;

                rdr = cmm.ExecuteReader();

                ObjectResult<spImportOrder_Result> results =
                    _sme.Translate<spImportOrder_Result>(rdr);
                gridErrors.ItemsSource = results;
                rdr.Close();
                if (cmm.Parameters["@ReturnValue"].Value != null)
                    importBatchID = (Int32)cmm.Parameters["@ReturnValue"].Value;

                if (importBatchID != 0)
                {
                    txtResults.Text = "Import batch ID: " + importBatchID.ToString();
                    tblImportBatch importBatch = (tblImportBatch)
                        _sme.GetObjectByKey(new System.Data.EntityKey("SalesManagerEntities.tblImportBatch", "ImportBatchID", importBatchID));
                    if (importBatch != null)
                    {
                        txtResults.Text += "\nLines read :" + importBatch.Lines +
                            "\nOrders loaded :" + importBatch.Imported;
                    }
                }
            }
            catch (Exception err)
            {
                this.Cursor = saveCursor;
                MessageBox.Show("Error importing orders.\n" + err.Message);
                if (rdr != null)
                    if (!rdr.IsClosed)
                        rdr.Close();
                return;
            }
            finally
            {
                this.Cursor = saveCursor;
            }
        }

        private void btnSpecs_Click(object sender, RoutedEventArgs e)
        {
            dlgSpecifications dlg = new dlgSpecifications();
            if ((bool)dlg.ShowDialog())
            {
                ((CollectionViewSource)FindResource("ImportSpecifications")).Source = (from c in _sme.tblImportSpec select c);
            }
        }

        private void btnHistory_Click(object sender, RoutedEventArgs e)
        {
            dlgHistory dlg = new dlgHistory();
            dlg.ShowDialog();
        }

        private void btnView_Click(object sender, RoutedEventArgs e)
        {
            if (cmbOwner.SelectedValue == null)
            {
                MessageBox.Show("Select a valid owner");
                return;
            }
            Int32 ownerID = (Int32)cmbOwner.SelectedValue;

            if (cmbImportSpec.SelectedValue == null)
            {
                MessageBox.Show("Select a valid import specification");
                return;
            }
            tblImportSpec importSpec = (tblImportSpec)cmbImportSpec.SelectedItem;

            if (!System.IO.File.Exists(txtFileName.Text))
            {
                MessageBox.Show("File not found.");
                return;
            }

            dlgViewFile dlg = new dlgViewFile(txtFileName.Text, importSpec.TemplateFile);
            dlg.ShowDialog();
        }

        private void btnSentinal_Click(object sender, RoutedEventArgs e)
        {
            dlgSentinals dlg = new dlgSentinals();
            dlg.ShowDialog();
        }
    }
}
